from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from .models import TimeCapsule
from .forms import TimeCapsuleForm
from django.utils import timezone
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import TimeCapsule
from django.http import HttpResponse


def time_capsule_view(request):
    print("View called!")
    return HttpResponse("Welcome to the Time Capsule!")
@login_required  # 确保只有登录用户可以访问
def profile(request):
    capsules = TimeCapsule.objects.filter(user=request.user)
    return render(request, 'capsules/profile.html', {'capsules': capsules})

def homepage(request):
    if 'visit_count' in request.session:
        request.session['visit_count'] += 1
    else:
        request.session['visit_count'] = 1
    visit_count = request.session['visit_count']

    capsules = []
    if request.user.is_authenticated:
        capsules = TimeCapsule.objects.filter(user=request.user)

    return render(request, 'capsules/home.html', {'visit_count': visit_count, 'capsules': capsules})

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('homepage')
    else:
        form = UserCreationForm()
    return render(request, 'capsules/register.html', {'form': form})


@login_required
def create_capsule(request):
    if request.method == 'POST':
        form = TimeCapsuleForm(request.POST)
        if form.is_valid():
            capsule = form.save(commit=False)
            capsule.user = request.user
            capsule.save()
            return redirect('dashboard')
    else:
        form = TimeCapsuleForm()
    return render(request, 'capsules/create_capsule.html', {'form': form})


@login_required
def dashboard(request):
    capsules = TimeCapsule.objects.filter(user=request.user)
    return render(request, 'capsules/dashboard.html', {'capsules': capsules})


@login_required
def view_capsule(request, pk):
    capsule = TimeCapsule.objects.get(pk=pk)
    if capsule.user != request.user:
        return redirect('dashboard')
    can_view = timezone.now() >= capsule.opening_date
    return render(request, 'capsules/view_capsule.html', {'capsule': capsule, 'can_view': can_view})


from django.shortcuts import render

# Create your views here.
